package com.treasure.hunt.mine

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ScreenUtils
import com.google.android.material.tabs.TabLayout
import com.module.lemlin.base.RecyclerViewHolder
import com.module.lemlin.base.loadCenterImage
import com.module.lemlin.base.loadCropImage
import com.module.lemlin.base.loadRoundImage
import com.module.lemlin.mode.ViewModeFragment
import com.module.lemlin.rxhttp.Status
import com.module.lemlin.rxhttp.msg
import com.treasure.hunt.R
import com.treasure.hunt.app.AppConstance
import com.treasure.hunt.entity.CardList
import com.treasure.hunt.mode.CardViewMode
import com.treasure.hunt.popup.DialogTurnPopup
import com.youth.banner.adapter.BannerAdapter
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.listener.OnPageChangeListener
import kotlinx.android.synthetic.main.fragment_card_change.*

class CardChangeFragment : ViewModeFragment<CardViewMode>() {

    companion object {
        private const val EXTRA_NAME_CARD = "EXTRA_NAME_CARD"
        fun newInstance(cardList: CardList): CardChangeFragment {
            val bundle: Bundle = Bundle().apply {
                putSerializable(EXTRA_NAME_CARD, cardList)
            }
            return CardChangeFragment().apply {
                arguments = bundle
            }
        }
    }

    private val turnPopup: DialogTurnPopup by lazy {
        DialogTurnPopup(context = requireContext(),
            onConfirm = {
                val cardList: CardList = (arguments?.getSerializable(EXTRA_NAME_CARD) as? CardList)
                    ?: return@DialogTurnPopup
                val cardListExChange: CardList =
                    viewModel.cardListLiveData.value?.httpData?.data?.filter { it.type != 2 }?.get(bvMineBanner.currentItem)
                        ?: return@DialogTurnPopup
                viewModel.cardExchange(cardList.id, cardListExChange.id)
            },
            onCancel = {
                turnPopup.dismiss()
            })
    }

    override val layoutResId: Int
        get() = R.layout.fragment_card_change

    override fun viewModel(): CardViewMode {
        return createViewModel(requireActivity())
    }

    override fun initView() {

        val height: Int =
            ((ScreenUtils.getAppScreenHeight() - ConvertUtils.dp2px(45f) - BarUtils.getStatusBarHeight()) / 5.8 * 3.8).toInt()

        bvMineBanner.layoutParams.apply {
            if (height > ConvertUtils.dp2px(360f)) {
                this.height = ConvertUtils.dp2px(360f)
            }
        }

        bvMineBanner.addOnPageChangeListener(object : OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) = Unit

            override fun onPageScrolled(
                position: Int, positionOffset: Float, positionOffsetPixels: Int
            ) = Unit

            override fun onPageSelected(position: Int) {
                tlMineCardKindBody.getTabAt(position)?.select()
            }
        })


        tlMineCardKindBody.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabReselected(tab: TabLayout.Tab?) = Unit

            override fun onTabUnselected(tab: TabLayout.Tab?) = Unit

            override fun onTabSelected(tab: TabLayout.Tab?) {
                bvMineBanner.currentItem = tab?.position ?: 0
            }
        })

        tvMineCardImmediately.setOnClickListener {
            val cardList: CardList = (arguments?.getSerializable(EXTRA_NAME_CARD) as? CardList)
                ?: return@setOnClickListener
            val cardListExChange: CardList =
                viewModel.cardListLiveData.value?.httpData?.data?.filter { it.type != 2 }?.get(bvMineBanner.currentItem)
                    ?: return@setOnClickListener
            turnPopup.setData(
                textTitle = "提示",
                textMessage = "确认将${cardList.title}转换成${cardListExChange.title}吗？",
                textConfirm = "立即转换",
                textCancel = "取消",
                src = cardList.image,
                srcExchange = cardListExChange.image
            ).showPopupWindow()
        }
    }

    override fun initViewMode() {
        viewModel.cardListLiveData.observe(this, Observer { response ->
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.data?.let { cardList ->
                fillData(cardList.filter { it.type != 2 }.toMutableList())
            }
        })

        viewModel.baseLiveData.observe(this, Observer { response ->
            if (response == null)
                return@Observer
            if (response.status == Status.FAILURE) {
                turnPopup.dismiss()
                toast(response.throwable?.msg ?: "未知错误")
                viewModel.baseLiveData.postValue(null)
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            toast("转换成功！")
            turnPopup.dismiss()
            viewModel.baseLiveData.postValue(null)
        })
    }

    private fun fillData(cardList: MutableList<CardList>) {

        bvMineBanner.addBannerLifecycleObserver(this)
            .setBannerGalleryEffect(38, 18)
            .isAutoLoop(false)
            .setAdapter(object : BannerAdapter<CardList, RecyclerViewHolder>(cardList) {
                override fun onCreateHolder(parent: ViewGroup, viewType: Int): RecyclerViewHolder {
                    val view: View = LayoutInflater.from(parent.context)
                        .inflate(R.layout.item_banner_card_2, parent, false)
                    return RecyclerViewHolder(view)
                }

                override fun onBindView(
                    holder: RecyclerViewHolder,
                    data: CardList,
                    position: Int,
                    size: Int
                ) {
                    holder.itemView.findViewById<ImageView>(R.id.ivBannerCardImage).apply {
                        val isHttps: Boolean = data.image.substring(0, 5).contains("http") ||
                                data.image.substring(0, 5).contains("https")
                        loadCenterImage("${if (isHttps) "" else AppConstance.URL_IMAGE}${data.image}")
                    }
                }
            }, (false))


        tlMineCardKindBody.apply {
            removeAllTabs()
            for ((index: Int, item: CardList) in cardList.withIndex()) {
                addTab(newTab().apply {
                    val view: View = LayoutInflater.from(requireContext())
                        .inflate(R.layout.item_card_kind, null)
                    val isHttps: Boolean = item.image.substring(0, 5).contains("http") ||
                            item.image.substring(0, 5).contains("https")
                    view.findViewById<ImageView>(R.id.ivCardKindIcon)
                        .loadRoundImage(
                            "${if (isHttps) "" else AppConstance.URL_IMAGE}${item.image}",
                            radius = 10
                        )
                    view.findViewById<TextView>(R.id.tvCardKindTitle).text = item.title
                    view.findViewById<TextView>(R.id.tvCardKindNum).text = item.num.toString()
                    customView = view
                    tag = index
                })
            }
        }
    }
}